<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="称重时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="车牌号码" prop="plantNo">
        <el-input
          v-model="queryParams.plantNo"
          placeholder="请输入车牌号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="场站名称" prop="stationName">
        <el-input
          v-model="queryParams.stationName"
          placeholder="请输入场站名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item label="是否超重" prop="isOverWeight">
        <el-select v-model="queryParams.isOverWeight" placeholder="请选择">
          <el-option
            v-for="dict in dict_isOverWeight"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item  label="所属区域" prop="areaCode">
        <el-select v-model="queryParams.areaCode"  placeholder="请选择">
          <el-option
            v-for="item in townData"
            :key="item.areaCode"
            :label="item.areaName"
            :value="item.areaCode"
          ></el-option>
        </el-select>

      </el-form-item>
       <el-form-item label="监管单位" prop ="supervisionUnit">
        <el-select v-model="queryParams.supervisionUnit" placeholder="请选择" clearable>
          <el-option
            v-for="dict in station_jgdw"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--<el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:record:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:record:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:record:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:record:export']"
        >导出</el-button>
      </el-col>
    </el-row>-->

    <el-table v-loading="loading" :data="recordList" :max-height="tableHeight" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="场站名称" align="left" prop="stationName" width="300px" />
      <el-table-column label="监管单位" align="center" prop="supervisionUnit" :formatter="supervisionUnitFormat" />
      <el-table-column label="车牌号码" align="center" prop="plantNo" />
      <el-table-column label="车牌颜色" align="center" prop="plantColor" />
      <el-table-column label="挂车号码" align="center" prop="plantNoGua" />
      <el-table-column label="称重时间" align="center" prop="weightTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.weightTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="称重总重(单位kg)" align="center" prop="grossWeight" />
      <!--<el-table-column label="核定总重(单位kg)" align="center" prop="CoTotalMass" />
      <el-table-column label="车轴数" align="center" prop="CoAxleNumber" />-->
<!--      <el-table-column label="是否超重(场站判定)" align="center" prop="isOverWeight" :formatter="isOverWeightFormat"/>-->
      <!--<el-table-column label="操作人" align="center" prop="operatorName" />-->
      <el-table-column label="所属区域" align="center" prop="areaCode" :formatter="converJurisdictionUnit"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['weight:record:query']"
          >详细</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleVideo(scope.row)"
            v-hasPermi="['weight:record:query']"
          >观看视频</el-button>

          <!--<el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:record:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:record:remove']"
          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="openView" width="1250px">
      <el-form ref="form" :model="form" label-position="right" label-width="140px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>管理信息</span>
          </div>
          <el-row>
            <el-col :span="12">
             <el-form-item label="场站名称：">{{form.stationName }}</el-form-item>
              <el-form-item label="场站编号：" >{{form.stationCode}}</el-form-item>
            </el-col>
          </el-row>

          <!--<el-col :span="12">
            <el-form-item label="称重设备编号：" >{{form.deviceCode}}</el-form-item>
            <el-form-item label="内部流水号：" >{{form.serialNumber}}</el-form-item>
          </el-col>-->
          <el-col :span="12">
            <el-form-item label="运单编号：" >{{form.goodsCode}}</el-form-item>
            <el-form-item label="称重时间：" >{{form.weightTime}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作人：" >{{form.operatorName}}</el-form-item>
          </el-col>
        </el-card>
   <br>
   <br>
   <br>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>称重信息</span>
          </div>
          <el-col :span="12">
             <el-form-item label="车牌号码：" >{{form.plantNo}}</el-form-item>
             <el-form-item label="车牌颜色：" >{{form.plantColor}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="称重总重(单位kg)：" >{{form.grossWeight}}</el-form-item>
            <el-form-item label="空重(单位kg)：" >{{form.emptyWeight}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="核定总重(单位kg)：" >{{form.CoTotalMass}}</el-form-item>
            <el-form-item label="净重(单位kg)：" >{{form.netWeight}}</el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="车轴数：" >{{form.CoAxleNumber}}</el-form-item>
            <!--<el-form-item label="是否超重：" >{{form.isOverWeight}}</el-form-item>-->
            <el-form-item label="是否超重(场站判定)：" >{{isOverWeightFormat(form)}}</el-form-item>

          </el-col>
          <el-row>
            <el-form-item label="挂车车牌：" >{{form.plantNoGua}}</el-form-item>
          </el-row>

          <el-row>
            <el-col :span="12">
              <!-- zPlatePhoto rearSidePhoto -->
              <el-form-item label="车辆侧前方图片:">
                <!--  <img src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png" class="image">-->
                <el-image :src="form.zPlatePhoto"></el-image>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="车辆侧后方图片:" v-if="form.rearSidePhoto == undefined || form.rearSidePhoto == ''">
                无
              </el-form-item>
              <el-form-item label="车辆侧后方图片:" v-else>
                <el-image :src="form.rearSidePhoto"></el-image>
              </el-form-item>
            </el-col>
          </el-row>

        </el-card>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="info_close">关闭</el-button>
      </div>
    </el-dialog>

    <div class="videoview" style="display:none;">
      <iframe width=0 height=0 id="url" :src="videoUrl"></iframe>
    </div>

    <el-dialog :title="title" :visible.sync="openVideoPlayer" width="800px" height="400px;">
    <!--在视频外面加一个容器-->
      <div class="input_video" id="video-content">
        <video
          id="myVideo"
          class="video-js"
        >
          <source
            src=""
            type=""
          >
        </video>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="openIframe" width="800px" height="400px;">
      <!--在视频外面加一个容器-->
      <div class="input_video">
        <iframe width="740px" height="400px" v-if="openIframe" :src="frUrl" frameborder=0 allowfullscreen></iframe>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listRecord, getRecord, delRecord, addRecord, updateRecord, exportRecord, getVideoPath } from "@/api/weight/record";

import { getBackVideoPath, getAreaListByUserId } from "@/api/weight/station";


export default {
  name: "Record",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      //字典-监管单位
      station_jgdw: [],
      // 称重记录表格数据
      recordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //称重弹窗
      openView: false,
      openVideoView: false,
      tableHeight: window.innerHeight - 300,
      //日期范围
      dateRange: [],
      // 是否超重
      dict_isOverWeight: [],

      townData: [],

      videoUrl: '',

      is_admin: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stationCode: undefined,
        deviceCode: undefined,
        serialNumber: undefined,
        goodsCode: undefined,
        stationName: undefined,
        weightTime: undefined,
        operatorName: undefined,
        plantNo: undefined,
        plantColor: undefined,
        grossWeight: undefined,
        emptyWeight: undefined,
        netWeight: undefined,
        isOverWeight: undefined,
        plantNoGua: undefined,
        zPlatePhoto: undefined,
        rearSidePhoto: undefined,
        areaCode: undefined,
        supervisionUnit:undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        stationCode: [
          { required: true, message: "场站编号不能为空", trigger: "blur" }
        ],
        deviceCode: [
          { required: true, message: "称重设备编号不能为空", trigger: "blur" }
        ],
        serialNumber: [
          { required: true, message: "称重业务内部流水号不能为空", trigger: "blur" }
        ],
        stationName: [
          { required: true, message: "场站名称不能为空", trigger: "blur" }
        ],
        weightTime: [
          { required: true, message: "称重时间不能为空", trigger: "blur" }
        ],
        operatorName: [
          { required: true, message: "操作人姓名不能为空", trigger: "blur" }
        ],
        plantNo: [
          { required: true, message: "车牌号码不能为空", trigger: "blur" }
        ],
        plantColor: [
          { required: true, message: "车牌颜色不能为空", trigger: "blur" }
        ],
        grossWeight: [
          { required: true, message: "总重(单位kg)不能为空", trigger: "blur" }
        ],
        emptyWeight: [
          { required: true, message: "空重(单位kg)不能为空", trigger: "blur" }
        ],
        netWeight: [
          { required: true, message: "净重(单位kg)不能为空", trigger: "blur" }
        ],
      },
      frUrl: '',
      openIframe: false,
      openVideoPlayer: false,
      myPlayer: undefined
    };
  },
  created() {
    let date = new Date();
    let today= this.timeFormat(date) //当前日期
    // 默认日期赋值
    this.dateRange = [today, today];

    const stationCode = this.$route.params && this.$route.params.stationCode;
    this.queryParams.stationCode=stationCode;
    this.getList();
    this.getDicts("is_over_weight").then(response => {
      this.dict_isOverWeight = response.data;
    });
    this.getDicts("station_jgdw").then((response) => {
      this.station_jgdw = response.data;
    });
    const roles = this.$store.getters && this.$store.getters.roles;
    for (let rol of roles){
      if ('admin'==rol){
        this.is_admin=true;
      }
    }

    getAreaListByUserId().then(response =>{
      this.townData=response.data;
    });

  },
  mounted() {

  },
  methods: {
    // 岗位状态字典翻译
    supervisionUnitFormat(row, column) {
      return this.selectDictLabel(this.station_jgdw, row.supervisionUnit);
    },
    /** 查询称重记录列表 */
    getList() {
      if(this.dateRange == null || this.dateRange.length  <= 0){
        this.msgInfo("请选择查询日期区间");
        return;
      }
      this.loading = true;
      listRecord(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 获取管辖地，属地 **/
    getTown(areaCode) {
      getTown(areaCode).then(response =>{
          this.townData=response.data;
      });
    },

    info_close() {
      this.openView =false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        stationCode: undefined,
        deviceCode: undefined,
        serialNumber: undefined,
        goodsCode: undefined,
        stationName: undefined,
        weightTime: undefined,
        operatorName: undefined,
        plantNo: undefined,
        plantColor: undefined,
        grossWeight: undefined,
        emptyWeight: undefined,
        netWeight: undefined,
        isOverWeight: undefined,
        plantNoGua: undefined,
        zPlatePhoto: undefined,
        rearSidePhoto: undefined,
        delFlag: undefined,
        createTime: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    initVideo(url,type) {
      if(document.getElementById("myVideo")==null || document.getElementById("myVideo").length <= 0 ){
        var videoContent = document.getElementById("video-content");
        videoContent.innerHTML = "<video\n" +
          "            id=\"myVideo\"\n" +
          "            class=\"video-js vjs-default-skin\"\n" +
          "          >\n" +
          "            <source\n" +
          "              src=\"\"\n" +
          "              type=\"\"\n" +
          "            >\n" +
          "          </video>";
      }
      //初始化视频方法
      let myPlayer = this.$video(myVideo, {
        //确定播放器是否具有用户可以与之交互的控件。没有控件，启动视频播放的唯一方法是使用autoplay属性或通过Player API。
        controls: true,
        //自动播放属性,muted:静音播放
        autoplay: "muted",
        //建议浏览器是否应在<video>加载元素后立即开始下载视频数据。
        preload: "auto",
        //设置视频播放器的显示宽度（以像素为单位）
        width: "740px",
        //设置视频播放器的显示高度（以像素为单位）
        height: "400px",
        playbackRates: [0.5, 1, 1.5, 2],
        controlBar: {
          playToggle: {
            replay: false
          },
          volumePanel: {
            inline: false
          }
        },
        sources: [{
          src: url,
          type: type
        }]
      });
      myPlayer.play();
      this.myPlayer = myPlayer;
    },
    handleVideo(row){
      // if(row.stationCode.indexOf("320205") > -1){    // 锡山调用电信视频
      //   let param={
      //     stationId: row.stationId,
      //     startTime: row.weightTime
      //   }
      //   getBackVideoPath(param).then(response => {
      //     this.videoUrl=response.data.videoUrl;
      //   });
      //
      //   setTimeout(() => {
      //     this.videoUrl='';
      //   }, 5000);
      // }else{
        getVideoPath(row.id).then(response => {
          if(this.myPlayer != null && this.myPlayer != undefined && this.myPlayer != ''){
            if(this.myPlayer.isDisposed()==false){
              this.myPlayer.dispose();
            }
          }
          if (response.code === 200) {
            const videoUrl=response.data.videoPath;
            if(row.stationCode.indexOf("320282") > -1){
                this.frUrl = videoUrl;
                this.openIframe = true;
            }else{
              this.openVideoPlayer = true;
              let type = "application/x-mpegURL";
              if(videoUrl.indexOf("mp4")> -1){
                type= 'video/mp4';
              }
              setTimeout(() => {
                this.initVideo(videoUrl,type);
              }, 100);
            }
          } else {
            this.msgError(response.msg);
          }
        });
    //  }

    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      let date = new Date();
      let today= this.timeFormat(date) //当前日期
      // 默认日期赋值
      this.dateRange = [today, today];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加称重记录";
    },
    //详细信息
    handleView(row) {
      this.reset();
      const id = row.id
      this.$router.push({
        path:"/weigh/recorddetail",
        query:{
          id:row.id
        }
      })
      // this.reset();
      // const id = row.id
      // console.info("id==="+id);
      // getRecord(id).then(response => {
      //   this.form = response.data;
      //   this.openView = true;
      //   this.title = "称重记录详细信息";
      // });

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRecord(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改称重记录";
      });
    },
    isOverWeightFormat(row,column) {
      return this.selectDictLabel(this.dict_isOverWeight, row.isOverWeight);
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateRecord(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addRecord(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除称重记录编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delRecord(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有称重记录数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportRecord(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    timeFormat: function (date) {
      if (!date || typeof(date) === "string") {
        this.error("参数异常，请检查...");
      }
      var y = date.getFullYear(); //年
      var m = date.getMonth() + 1; //月
      var d = date.getDate(); //日

      return y + "-" + (m < 10 ? '0' + m : m) + "-" + (d < 10 ? '0' + d : d);
    },
    // 所属区域转换
    converJurisdictionUnit(row,column){
      let areaName = '';
      this.townData.forEach(function (_val,index) {
        if(row.areaCode==_val.areaCode){
          areaName = _val.areaName;
          return true;
        }
      });
      return areaName;
    },
  }
};
</script>
